package com.sunlands.zlcx.usercenter.controller;

import com.sunlands.zlcx.usercenter.common.annotation.AutoLog;
import com.sunlands.zlcx.usercenter.exception.GlobalExceptionHandler;
import com.sunlands.zlcx.usercenter.service.TencentImageCheckServiceImpl;
import com.sunlands.zlcx.usercenter.service.UploadService;
import com.sunlands.zlcx.usercenter.vo.response.BusinessResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.util.Pair;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import static com.sunlands.zlcx.usercenter.vo.CommonResultMessage.*;

/**
 * @author anjl
 * @date 5:38 PM 2019/6/13
 * description:
 */
@SuppressWarnings("unused")
@Api(tags = "6、上传", position = 6)
@ApiResponses(value = {@ApiResponse(code = 400, response = GlobalExceptionHandler.class, message = "数据校验失败"), @ApiResponse(code = 500, response = GlobalExceptionHandler.class, message = "内部错误")})
@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController implements AuthSupport{

    @AutoLog
    @ApiOperation(value = "上传头像", notes = "上传成功之后, 返回文件地址")
    @PreAuthorize("isAuthenticated()")
    @PostMapping("/avatar-url")
    public BusinessResult<String> upload(@RequestParam("file") MultipartFile file) throws IOException {

        StopWatch stopWatch = new StopWatch();
        stopWatch.start("check file");
        //检查文件是否为空
        if(file.isEmpty()) {
            return BusinessResult.createInstance(PARAMS_NOT_NULL, "请选择图片！");
        }

        String fileName = new String(file.getOriginalFilename().getBytes(), StandardCharsets.UTF_8);
        if(file.getSize() > AVATAR_URL_MAX_SIZE){
            return BusinessResult.createInstance(FILE_SIZE_LIMIT, "图片大小不能超过" + AVATAR_URL_MAX_SIZE + " byte");
        }

        //检查是否是图片
        BufferedImage bi = ImageIO.read(file.getInputStream());
        if(bi == null){
            return BusinessResult.createInstance(FILE_TYPE_LIMIT, "必须上传图片类型的文件");
        }
        stopWatch.stop();
        stopWatch.start("upload file");


        Pair<String, String> pair = uploadService.uploadOssFile(file, MODEL_PATH, SUB_MODEL_PATH, false);
        stopWatch.stop();
        log.debug("stopWatch = {}", stopWatch.prettyPrint());

        Boolean flag = tencentImageCheckService.checkImg(pair.getFirst());
        if(flag){
            uploadService.deleteFile(pair.getSecond());
            return BusinessResult.createInstance(IMAGE_VIOLATION);
        }
        return BusinessResult.createSuccessInstance(pair.getFirst());
    }

    @Autowired
    private UploadService uploadService;
    @Autowired
    private TencentImageCheckServiceImpl tencentImageCheckService;
    public static final String MODEL_PATH = "tongzhuo";
    private static final String SUB_MODEL_PATH = "avatar";
    private static final long AVATAR_URL_MAX_SIZE =   1024 * 1024 * 5;
}
